package com.imcrl.piano.core
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	
	public class BitmapAssets
	{
		protected var source:BitmapData;
		
		
		private var total:int;
		
		protected var assets:Vector.<BitmapData>;
		public function BitmapAssets(total:int)
		{
			this.total=total;
			
			assets=new Vector.<BitmapData>();
		}
		
		public function load(url:String):void{
			var loader:Loader=new Loader();
			loader.addEventListener(Event.COMPLETE,completeHandler);
			loader.load(new URLRequest(url));
		}
		
		private function completeHandler(event:Event):void{
			var target:DisplayObject=(event.target as Loader).content;
			
			var bitmapdata:BitmapData
			if(target is Bitmap){
				bitmapdata=(target as Bitmap).bitmapData;
			}else{
				bitmapdata=new BitmapData(target.width,target.height,true,0);
				bitmapdata.draw(target);
				
			}
			this.setAsset(bitmapdata);
		}
		
		public function setAsset(bitmapdata:BitmapData):void{
			this.source=bitmapdata;
			
			assets.splice(0,assets.length);
			
			spliceAsset();
		}
		
		public function get(code:int):BitmapData{
			return assets[code];
		}
		
		
		protected function spliceAsset():void{
			var sw:int=int(source.width/total);
			var sh:int=source.height;
			
			var bitmapdata:BitmapData;
			var rect:Rectangle=new Rectangle(0,0,sw,sh);
			var p:Point=new Point();
			for(var i:int=0;i<total;i++){
				rect.x=i*sw;
				bitmapdata=new BitmapData(sw,sh,true,0);
				bitmapdata.copyPixels(source,rect,p);
				
				assets.push(bitmapdata);
			}
		}
		
	}
}